//
//  RHPolicySettingVC.m
//  RuiHeAppApp
//
//  Created by Yan Chen on 2024/3/12.
//

#import "RHPolicySettingVC.h"
#import "RHPolicyModeCell.h"
#import "RHPolicyModeModel.h"
#import "SYChartTool.h"
#import "RHChoicePolicyModeView.h"
#import "RHPolicyConfigCell.h"
#import "RHPolicyConfigView.h"
#import "RHPolicySocCell.h"
#import "RHPolicyFeedCell.h"
#import "RHEndPointModel.h"

@interface RHPolicySettingVC ()<UITableViewDelegate,UITableViewDataSource>
//@property (nonatomic ,strong) NSArray *policyDataArr;

@property (nonatomic ,strong) UITableView *tableView;

@property (nonatomic ,strong) RHPolicyModeModel *curMode;

@property (nonatomic ,strong) NSArray *policyModeArr;

@property (nonatomic ,strong) QMUIButton *lastBtn;
//时间段
@property (nonatomic ,assign) NSInteger timeIndex;

@property (nonatomic ,strong) NSArray *timeArr;

@property (nonatomic ,strong) UIView *timeView;

@property (nonatomic ,assign) NSInteger curModeIndex;

@property (nonatomic ,copy) NSString *emuSN;
@end

@implementation RHPolicySettingVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"策略配置".rh_localized;
    self.view.backgroundColor = CFTabViewBgColor;
    [self getEmuInfo];
    [self setupUI];
    [self createTimeArr];
    self.curModeIndex = 0;
}

-(void)setCurModeIndex:(NSInteger)curModeIndex
{
    _curModeIndex = curModeIndex;
    self.tableView.tableFooterView = [self footView];
    [self createPolicyMode];
}

-(void)createTimeArr
{
    NSMutableArray *tempArr = [NSMutableArray array];
    NSArray *timeArr = [SYChartTool loadJsonFileWithName:@"policyMode_Times"];
    [timeArr enumerateObjectsUsingBlock:^(NSArray  *_Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSArray *arr = [NSArray yy_modelArrayWithClass:[RHPolicyModeModel class] json:obj];
        [tempArr addObject:arr];
    }];
    self.timeArr = tempArr.copy;
}

-(void)createPolicyMode
{
     
    NSArray *jsonFileArr = @[@"policyMode_None",
                             @"policyMode_selfUse",
                             @"policyMode_peakLoadShift",
                             @"policyMode_PvPriority",
                             @"policyMode_MainsPriority",
                             @"policyMode_BackupMode",
                             @"policyMode_BatteryMode"];
    NSArray *arr = [SYChartTool loadJsonFileWithName:jsonFileArr[self.curModeIndex]];
    self.policyModeArr = [NSArray yy_modelArrayWithClass:[RHPolicyModeModel class] json:arr];
    //削峰填谷 默认选中第一组时间段
    if(self.curModeIndex == 2){
        RHPolicyModeModel *sectionModel = self.policyModeArr[1];
        sectionModel.rows = [self.timeArr firstObject];
    }
    
}

- (void)setupUI{
   
    _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    _tableView.backgroundColor = CFTabViewBgColor;
    [_tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    [_tableView registerClass:[RHPolicyModeCell class] forCellReuseIdentifier:@"RHPolicyModeCell"];
    [_tableView registerClass:[RHPolicyConfigCell class] forCellReuseIdentifier:@"RHPolicyConfigCell"];
    [_tableView registerClass:[RHPolicySocCell class] forCellReuseIdentifier:@"RHPolicySocCell"];
    [_tableView registerClass:[RHPolicyFeedCell class] forCellReuseIdentifier:@"RHPolicyFeedCell"];
    [_tableView setDelegate:self];
    [_tableView setDataSource:self];
    [self.view addSubview:_tableView];
    
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.insets(UIEdgeInsetsZero);
    }];
    
    if (@available(iOS 11.0, *)) {
        _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }
    
    if (@available(iOS 15.0, *)) {
        _tableView.sectionHeaderTopPadding = 0;
    }
    
}

-(UIView*)timeViewWithModel:(RHPolicyModeModel*)sectionModel
{
    if(!_timeView){
        _timeView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kUI_WINDOW_W, 45)];
        UIScrollView *scrollView = [[UIScrollView alloc]init];
        scrollView.showsHorizontalScrollIndicator = NO;
        scrollView.contentInset = UIEdgeInsetsMake(0, 15, 0, 15);
        [_timeView addSubview:scrollView];
        UIView *scrollContentView = kView;
        [scrollView addSubview:scrollContentView];
        [scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.insets(UIEdgeInsetsZero);
        }];
        [scrollContentView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.insets(UIEdgeInsetsZero);
            make.height.equalTo(scrollView);
        }];
        

        __block QMUIButton *lastItem;
        [sectionModel.typeArr enumerateObjectsUsingBlock:^(NSString * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            QMUIButton *btn = [[QMUIButton alloc]init];
            [btn setTitle:obj forState:UIControlStateNormal];
            btn.titleLabel.font = kSYSTEMFONT(14);
            [btn setTitleColor:[UIColor colorWithHexString:@"3F4443" alpha:0.8] forState:UIControlStateNormal];
            btn.backgroundColor = kCOLOR_HEX(@"F6F8FA");
            btn.layer.cornerRadius = 8;
            btn.userInteractionEnabled = YES;
            [btn setBackgroundColor:kCOLOR_HEX(@"FFFFFF")];
            [scrollContentView addSubview:btn];
            
            [btn mas_makeConstraints:^(MASConstraintMaker *make) {
                make.width.offset(100);
                
                if(lastItem){
                    make.left.equalTo(lastItem.mas_right).offset(15);
                    make.top.bottom.equalTo(lastItem);
                }else{
                    make.left.top.bottom.mas_offset(0);
                }
            }];
            if(idx == sectionModel.typeArr.count-1){
                [btn mas_makeConstraints:^(MASConstraintMaker *make) {
                    make.right.mas_offset(0);
                }];
                
            }
            lastItem = btn;
            kWeakSelf;
            [[btn rac_signalForControlEvents:UIControlEventTouchUpInside]subscribeNext:^(__kindof UIControl * _Nullable x) {
                weakSelf.timeIndex = idx;
                sectionModel.rows = weakSelf.timeArr[weakSelf.timeIndex];
                [weakSelf.tableView reloadData];
            }];
            
            [RACObserve(self, timeIndex) subscribeNext:^(id  _Nullable x) {
                if([x integerValue] == idx){
                    [btn setTitleColor:[UIColor colorWithHexString:@"ffffff" alpha:1] forState:UIControlStateNormal];
                    [btn setBackgroundColor:CMainColorGreen];
                }else{
                    [btn setTitleColor:[UIColor colorWithHexString:@"3F4443" alpha:0.6] forState:UIControlStateNormal];
                    [btn setBackgroundColor:kCOLOR_HEX(@"FFFFFF")];
                }
            }];
       
        }];
    }
    return _timeView;
}

-(UIView*)footView
{
    kWeakSelf;
    UIView *footerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kUI_WINDOW_W, 60+kSafe_bottom)];
    if(self.curModeIndex == 0){
        UIImageView *img = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"policy_none"]];
        img.contentMode = UIViewContentModeCenter;
        footerView.height = 60 + 500;
        [footerView addSubview:img];
        [img mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.left.right.mas_offset(0);
            make.height.offset(60 + 300 - kScaleW(45));
        }];
        QMUILabel *lab = [[QMUILabel alloc]init];
        lab.text = @"暂无内容".rh_localized;
        lab.textAlignment = NSTextAlignmentCenter;
        lab.textColor = kCOLOR_HEX_A(@"3F4443", 0.3);
        lab.font = kSYSTEMFONT(14);
        [footerView addSubview:lab];
        [lab mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_offset(10);
            make.right.mas_offset(-10);
            make.centerY.equalTo(img).offset(80);
        }];
    }
    QMUIButton *finishBtn = [[QMUIButton alloc]init];
    [finishBtn setCornerRadius:8];
    [finishBtn setTitle:@"完成".rh_localized forState:UIControlStateNormal];
    finishBtn.titleLabel.font = kSYSTEMFONT(18);
    [finishBtn setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
    [finishBtn setBackgroundColor:CMainColorGreen];
    [footerView addSubview:finishBtn];
    
    
    [finishBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(15);
        make.right.mas_offset(-15);
        make.height.offset(kScaleW(45));
        make.bottom.offset(kSafe_bottom>0?-kSafe_bottom:-10);
       
    }];
    
    [[finishBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
       
        [weakSelf policyConfig];
    }];
    return footerView;
}

#pragma mark ------ network ---------

-(void)getEmuInfo
{
    [QMUITips showLoadingInView:self.view];
       NSDictionary *para = @{@"deviceId":ValidNullData(self.devModel.deviceId),
                              @"endpointTypeCode":@[@"EMU"],
                              @"group":@(1)};
    [RHEndPointModel startWithCompletionAPIKey:H_getEndpointByType argument:para requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        if(resultModel.code == 200){
            if([request.responseJSONObject[@"data"] isKindOfClass:[NSArray class]]){
                NSArray *dataArr = request.responseJSONObject[@"data"];
                NSDictionary *dataDic = [dataArr firstObject];
                if([dataDic[@"endpointList"] isKindOfClass:[NSArray class]]){
                    NSArray *endPointArr = dataDic[@"endpointList"];
                    NSDictionary *endpointDic = [endPointArr firstObject];
                    self.emuSN = endpointDic[@"sn"];
                }
            }
        }
        
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        
        
    }];
}

-(void)policyConfig
{
    if(self.emuSN.length == 0){
        [QMUITips showInfo:@"sn error"];
//        return;
    }
    
    NSMutableDictionary *requestPara = [NSMutableDictionary dictionary];
    //参数的头部
    NSTimeInterval interval = [[NSDate date] timeIntervalSince1970]*1000;
    NSString *timeStr = [NSString stringWithFormat:@"%@-%ld",self.devModel.deviceId,(NSInteger)interval];
    NSDictionary *headContent = @{
        @"cmdId": timeStr,
        @"deviceId": self.devModel.deviceId,
        @"deviceType": @"",
        @"messageType": @"1",//下行
        @"namespace": @"M_control",
        @"payloadVersion": @(0),
        @"timestamp": @((NSInteger)interval)
      };
    [requestPara setValue:headContent forKey:@"protocolHead"];
    //参数的body
    NSMutableDictionary *bodyDic = [NSMutableDictionary dictionary];
    NSMutableArray *paraListArr = [NSMutableArray array];
    
    if(self.curModeIndex == 2){
        //削峰填谷
        NSArray *arr = self.timeArr[self.timeIndex];
        
        [arr enumerateObjectsUsingBlock:^(RHPolicyModeModel  *_Nonnull model, NSUInteger idx, BOOL * _Nonnull stop) {
            NSString *power_key = [NSString stringWithFormat:@"Emu_PwrSeg%ld",idx + 1 + (self.timeIndex * 6)];
            NSString *soc_key = [NSString stringWithFormat:@"Emu_EndSocSeg%ld",idx + 1 + ( self.timeIndex * 6)];
           
            if(model.power.length > 0){
                NSMutableDictionary *mtbDic = [NSMutableDictionary dictionary];
                [mtbDic setObject:power_key forKey:@"paramName"];
                [mtbDic setObject:model.power forKey:@"value"];
                [paraListArr addObject:mtbDic];
            }
            if(model.soc.length > 0){
                NSMutableDictionary *mtbDic = [NSMutableDictionary dictionary];
                [mtbDic setObject:soc_key forKey:@"paramName"];
                [mtbDic setObject:model.soc forKey:@"value"];
                [paraListArr addObject:mtbDic];
            }
        
        }];
    }else{
        [self.policyModeArr enumerateObjectsUsingBlock:^(RHPolicyModeModel  *_Nonnull model, NSUInteger idx, BOOL * _Nonnull stop) {
           
            [model.rows enumerateObjectsUsingBlock:^(RHPolicyModeModel  *_Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                if(obj.paraKey){
                    if(obj.soc.length>0){
                        NSMutableDictionary *mtbDic = [NSMutableDictionary dictionary];
                        [mtbDic setObject:obj.paraKey forKey:@"paramName"];
                        [mtbDic setObject:obj.soc forKey:@"value"];
                        [paraListArr addObject:mtbDic];
                        
                    }
                    if(obj.content.length>0){
                        NSMutableDictionary *mtbDic = [NSMutableDictionary dictionary];
                        [mtbDic setObject:obj.paraKey forKey:@"paramName"];
                        [mtbDic setObject:obj.content forKey:@"value"];
                        [paraListArr addObject:mtbDic];
                    }
                }
            }];
            
        }];
    }
    
    
    //模式
    
    [paraListArr addObject:@{@"value":@(self.curModeIndex),
                             @"paramName":@"Emu_WorkMode"
                           }];

    [bodyDic setObject:paraListArr forKey:@"commandParamList"];
    [requestPara setValue:bodyDic forKey:@"protocolBody"];
    
    [QMUITips showLoading:@"setting..." inView:self.view];
    [BaseModel startWithCompletionAPIKey:H_controlDevice argument:requestPara requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        if(resultModel.code == 200){
            [QMUITips showSucceed:@"successful"];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self.tableView beginHeaderRefresh];
            });
        }
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        
    }];
}



#pragma mark - UITableViewDelegate,UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    
   
    return self.policyModeArr.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    RHPolicyModeModel *mode = self.policyModeArr[section];
    if([mode.type isEqualToString:@"peak_load"]){
//        NSArray *times = self.timeArr[self.timeIndex];
//        return times.count;
    }
    return mode.rows.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    RHPolicyModeModel *mode = self.policyModeArr[section];
    if(mode.sectionTitle.length>0){
        if(mode.typeArr.count>0){
            return 110;
        }
        return 40;
    }
    return 5;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.0;
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    RHPolicyModeModel *mode = self.policyModeArr[section];
    if(mode.sectionTitle.length>0){
        UIView *headView = [[UIView alloc]init];
        headView.frame = CGRectMake(0, 0, kUI_WINDOW_W, 40);
        QMUILabel *titleLab = [[QMUILabel alloc]init];
        titleLab.text = mode.sectionTitle.rh_localized;
        titleLab.font = kSYSTEMFONT(16);
        titleLab.textColor = kCOLOR_HEX(@"3F4443");
        [headView addSubview:titleLab];
        [titleLab mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_offset(15);
            make.left.mas_offset(15);
            make.right.mas_offset(-15);
        }];
        
        if(mode.typeArr.count>0){
            headView.frame = CGRectMake(0, 0, kUI_WINDOW_W, 90);
            //削峰填谷充放电时间段
            [headView addSubview:[self timeViewWithModel:mode]];
            [self.timeView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.right.mas_offset(0);
                make.height.offset(45);
                make.top.equalTo(titleLab.mas_bottom).offset(15);
            }];
        }
        return headView;
    }
    
    return nil;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    return nil;
}




- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    kWeakSelf;
    RHPolicyModeModel *sectionModel = self.policyModeArr[indexPath.section];
    RHPolicyModeModel *rowModel = sectionModel.rows[indexPath.row];
    if([rowModel.type isEqualToString:@"mode"]){
        RHPolicyModeCell *modeCell = [tableView dequeueReusableCellWithIdentifier:@"RHPolicyModeCell"];
        modeCell.mode = sectionModel;
        modeCell.selectionStyle = UITableViewCellSelectionStyleNone;
        return modeCell;
    }
    //削峰填谷
    if([rowModel.type isEqualToString:@"peak_load"]){
        RHPolicyConfigCell *configCell = [tableView dequeueReusableCellWithIdentifier:@"RHPolicyConfigCell"];
        configCell.timeLab.text = rowModel.time.rh_localized;
        configCell.configBlock = ^{
            RHPolicyConfigView *configView = [[RHPolicyConfigView alloc]init];
            configView.curMode = rowModel;
            kWeakSelf;
            configView.sureBlock = ^(RHPolicyModeModel * _Nonnull model) {
                [weakSelf.tableView reloadData];
            };
            [configView showAnimation];
        };
        configCell.policyModel = rowModel;
        return configCell;
    }
    //自发自用
    if([rowModel.type isEqualToString:@"self_use"]){
        RHPolicySocCell *socCell = [tableView dequeueReusableCellWithIdentifier:@"RHPolicySocCell"];
        socCell.policyModel = rowModel;
        return socCell;
    }
    
    if([rowModel.type isEqualToString:@"switch"]){
        RHPolicyFeedCell *feedCell = [tableView dequeueReusableCellWithIdentifier:@"RHPolicyFeedCell"];
        feedCell.policyModel = rowModel;
        return feedCell;
    }
   
    
    return [UITableViewCell new];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
   
    RHPolicyModeModel *model = self.policyModeArr[indexPath.section];
    RHPolicyModeModel *rowModel = model.rows[indexPath.row];
    if([rowModel.type isEqualToString:@"mode"]){
        RHChoicePolicyModeView *choiceView = [[RHChoicePolicyModeView alloc]init];
        choiceView.policyList = rowModel.typeArr;
        choiceView.curMode = self.curModeIndex;
        kWeakSelf;
        choiceView.choiceResultBlock = ^(NSInteger  mode) {
            weakSelf.curModeIndex = mode;
            [weakSelf.tableView reloadData];
        };
        [choiceView showAnimation];
    }
    

}



@end
